package org.visionlibrary.image.filters.dithering;

import java.util.Random;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class RandomDithering extends AbstractFilter {
	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);
		
		Random random = new Random();

		int maxX = src.getWidth();
		int maxY = src.getHeight();
		for (int ch = 0; ch < src.getNumBands(); ch++) {
			for (int x = 0; x < maxX; x++)
				for (int y = 0; y < maxY; y++) {
					int val = src.getSample(x, y, ch);
					int rand = random.nextInt(255);
					if (val <= rand)
						dest.setSample(x, y, ch, 0);
					else
						dest.setSample(x, y, ch, 255);
				}
		}
		return dest;
	}
}
